<!--  -->
<template>
  <div>
    <el-switch v-model="draggable" active-color="#13ce66" inactive-color="#ff4949" active-text="开启拖拽" inactive-text="关闭拖拽"></el-switch>
    <el-button type="danger" @click="batchDelete()">批量删除</el-button>
    <el-tree :data="menus" :props="defaultProps" :expand-on-click-node="false" show-checkbox node-key="id" :default-expanded-keys="expandedKey" :draggable="draggable" :allow-drop="allowDrop" ref="menuTree">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="node.level <= 2" type="text" size="mini" @click="() => append(data)">
            Append
          </el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">
            Edit
          </el-button>
          <el-button v-if="node.childNodes.length == 0" type="text" size="mini" @click="() => remove(node, data)">
            Delete
          </el-button>
        </span>
      </span>
    </el-tree>
    <!-- 对话框 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%" :append-to-body="false">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.unit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},

  data() {
    return {
      draggable: false,
      title: " ", //提示消息
      maxLevel: 1, //节点的最大深度
      dialogVisible: false, //对话框是否显示
      category: {
        dialogType: "", //判断 add和edit的标志
        id: null,
        name: "",
        parentId: 0,
        cateLevel: 1,
        icon: "",
        unit: "",
        status: 1,
        sort: 0,
      },
      menus: [],
      expandedKey: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  //所有方法
  methods: {
    //获取数据列表
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        console.log("成功获取菜单数据", data.data);
        this.menus = data.data;
      });
    },
    //添加数据
    append(data) {
      this.dialogVisible = true;
      this.title = "添加分类";
      this.category.dialogType = "add";
      this.category.id = null;
      this.category.name = "";
      this.category.parentId = data.id;
      this.category.cateLevel = data.cateLevel * 1 + 1;
      this.category.icon = "";
      this.category.unit = "";
      this.category.sort = 0;
      console.log("append", data);
    },
    //添加三级分类菜单的方法
    addCategory() {
      console.log("三级分类菜单", this.category);
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        //删除成功显示提示消息
        this.$message({
          message: "操作成功",
          type: "success",
        });
        //刷新菜单
        this.getMenus();
        //设置默认展开的菜单:
        this.expandedKey = [this.category.parentId];
      });
      //保存成功关闭对话框
      this.dialogVisible = false;
    },
    edit(data) {
      console.log("当前数据:", data);
      this.dialogVisible = true;
      this.title = "修改分类";
      this.category.dialogType = "edit";

      //todo 实时获取数据库中的数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.id}`),
        method: "get",
      }).then(({ data }) => {
        //请求成功
        console.log("要回显的数据：", data);
        this.category.id = data.data.id;
        this.category.name = data.data.name;
        this.category.icon = data.data.icon;
        this.category.unit = data.data.unit;
        this.category.parentId = data.data.patentId;
      });
    },
    editCategory() {
      //解构表达式（如果key与原数据相同可以省略）
      let { id, name, icon, unit } = this.category;
      this.$http({
        //es6新特性：1.数据解构  2. 反引号：``
        url: this.$http.adornUrl(`/product/category/update`),
        method: "post",
        data: this.$http.adornData({ id, name, icon, unit }, false),
      }).then(() => {
        //成功显示提示消息
        this.$message({
          message: "操作成功",
          type: "success",
        });
        //刷新菜单
        this.getMenus();
        //设置默认展开的菜单:
        this.expandedKey = [this.category.parentId];
      });
    },
    //提交请求的功能
    submitData() {
      if (this.category.dialogType == "add") {
        this.addCategory();
      }
      if (this.category.dialogType == "edit") {
        this.editCategory();
      }
      this.dialogVisible = false;
    },
    //删除节点
    remove(node, data) {
      //删除之前的确认弹框
      this.$confirm(`是否删除【${data.name}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //获取所有被选中的id值
          let ids = [data.id];
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            //删除成功显示提示消息
            this.$message({
              message: "操作成功",
              type: "success",
            });
            //刷新菜单
            this.getMenus();
            //设置默认展开的菜单:
            this.expandedKey = [node.parent.data.id];
          });
        })
        .catch(() => {});

      console.log("remove", node, data);
    },
    batchDelete() {
      let catIds = [];
      let checkedNodes = this.$refs.menuTree.getCheckedNodes();
      //es6新语法
      for (let element of checkedNodes) {
        catIds.push(element.id);
      }
      console.log("需要删除的元素id:", catIds);
      //删除之前的确认弹框
      this.$confirm(`是否删除【${catIds}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false),
          }).then(({ data }) => {
            //删除成功显示提示消息
            this.$message({
              message: "操作成功",
              type: "success",
            });
            //刷新菜单
            this.getMenus();
          });
        })
        .catch(() => {});
    },
    /**
     * 节点拖拽功能
     *
     * draggingNode: 拖拽的节点
     * dropNode：目标节点
     * type：拖拽类型
     */
    allowDrop(draggingNode, dropNode, type) {
      //被拖动的当前节点的总层数 以及 父节点总层数不能大于3
      console.log("allowDrop", draggingNode, dropNode, type);
      //计算当前节点的深度
      this.countNodeLevel(draggingNode);
      console.log("深度为:", this.maxLevel);
      // 当前节点的层级数 = 当前节点的最大深度 - 当前节点的深度 + 1;
      console.log("当前节点深度", draggingNode.level);
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
      console.log("节点深度为:", deep);
      // 判断拖拽的类型
      if (type == "inner") {
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }
    },
    //递归查询当前节点的最大深度
    countNodeLevel(node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let index = 0; index < node.childNodes.length; index++) {
          if (node.childNodes[index].level > this.maxLevel) {
            console.log("孩子节点为：", node.childNodes[index].level);
            this.maxLevel = node.childNodes[index].level;
          }
          //递归调用本位置存在异常需要处理
          this.countNodeLevel(node.childNodes[index]);
        }
      }
    },
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  //watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getMenus();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  //生命周期 - 创建之前
  beforeCreate() {},
  //生命周期 - 挂载之前
  beforeMount() {},
  //生命周期 - 更新之前
  beforeUpdate() {},
  //生命周期 - 更新之后
  updated() {},
  //生命周期 - 销毁之前
  beforeDestroy() {},
  //生命周期 - 销毁完成
  destroyed() {},
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated() {},
};
</script>
<style lang='scss' scoped>
</style>